<?php
/**
 * Created by PhpStorm.
 * CeshiUser: kevin
 * Date: 2018/1/3
 * Time: 13:13
 */

namespace app\index\model\pay;
//use app\common\model\TradeRecord;
use think\Exception;
//use app\common\model\CeshiUser;
//use app\common\model\UserOrder;
//use app\index\model\SmsBaoModel;
//use think\Db;

/**
 * 支付类
 *
 * @property int $uid 用户id
 * @property string $orderNumber 订单号
 * @property string $method 支付方式
 * @property number $money 支付金额
 * @property string $title 支付标题
 * @property bool $debug 调试模式
 */
class BasePay{
    public $uid;
    public $orderNumber;
    public $method;
    public $money;
    public $debug = false;

    /**
     * BasePay constructor.
     * @param array $config
     */
    public function __construct($config = [])
    {
        foreach ($config as $name => $value) {
            $this->$name = $value;
        }
    }
    /**
     * 支付完成处理
     */
    public function complete($tradeNo){
        if($this->payOrder($tradeNo)){
            return true;
        }
        return false;
    }

    /**
     * 支付结果
     */
    public function result(){

        return $this->getOrder(1) && $this->getRecord();
    }

    /**
     * 处理订单
     */
    protected function payOrder($tradeNo){
        Db::startTrans();
        try{
            $order = $this->getOrder(0);
            if($order){
                if($order['type'] == 3){
                    $orderModel = new UserOrder();
                    $list = $orderModel->where(['pid'=>$order['id'],'status'=>'0',])->field('id')->select()->toArray();
                    foreach ($list as $k=>$v){
                        $_list[] = ['id'=>$v['id'],'status'=>1];
                    }
                    if(!$orderModel->saveAll($_list)){
                        throw new Exception('拆分处理订单失败');
                    }
                }
                $order['status'] = '1';
                if($order->save()){
                    //更新交易记录
                    if(!$this->insertRecord($tradeNo)){
                        throw new Exception('更新交易记录表失败');
                    }
                    //发送短信
                    $this->sendSms();
                }else{
                    throw new Exception('订单更新失败');
                }
            }else{
                throw new Exception('没有找到符合的订单数据');
            }
            // 提交事务
            Db::commit();
            return true;
        } catch (Exception $e) {
            $text = $e->getMessage();
            //文件日志
            Pay::fileLog($text, 'debug.log');
            // 回滚事务
            Db::rollback();
        }

    }


    /**
     * 插入交易记录
     */
    protected function insertRecord($tradeNo){
        $data['order_number']=$this->orderNumber;
        $data['uid']=$this->uid;
        $data['trade_no']=$tradeNo;
        $data['money']=$this->getMoney();
        $data['method']=$this->method;
        if(TradeRecord::create($data)){
            return true;
        }
        return false;
    }

    /**
     * 发送短信提醒
     */
    protected function sendSms(){
        //发送短信
        $sms = new SmsBaoModel();
        //手机号码以后有服务老师修改
        $mobile = '13764663632';
        $username = User::get($this->uid)->username;
        $massage = '【中彧招牌】亲爱的李总,用户'.$username.'购买了商品,请注意安排人员查收!';
        $sms->SendSms($mobile, $massage);
    }


    /**
     * 获取订单
     */
    public function getOrder($status=false){

        $order = UserOrder::get(['order_number'=>$this->orderNumber, 'uid'=>$this->uid]);
        if($status !== false){
            $order = UserOrder::get(['order_number'=>$this->orderNumber, 'uid'=>$this->uid,'status'=>$status]);
        }
        return $order ?: false;
    }

    /**
     * 获取交易记录
     */
    public function getRecord(){
        $model = new TradeRecord();
        $record = $model->where(['order_number'=>$this->orderNumber, 'uid'=>$this->uid])->find();
        return $record ?: false;
    }

    /**
     * 获取支付金额，单位元
     */
    public function getMoney(){
        if($this->debug){
            return 0.01;
        }
        if($this->money !== null){
            return $this->money;
        }
        $this->money = $this->getOrder()->order_money;
        return $this->money;
    }

    /**
     * 获取支付相关url
     */
    public function getUrl(){
        return [
            'notifyUrl'=>"http://www.importndsf.com/import_nbsm/nbsm_shopping/public/index.php/index/Wxpay/notify"
        ];
        /*$params = $this->encodeParams();
        switch($this->method){
            case 'alipay':
                return [
                    'notifyUrl'=>'http://pz.zyholding.group/index.php/index/userpay/notify?params='.$params,
                    'returnUrl'=>'http://pz.zyholding.group/index.php/index/userpay/paysuccess?params='.$params
                ];
                break;
            case 'wxpay':
                return [
                    'notifyUrl'=>"http://pz.zyholding.group/index.php/index/userpay/notify"
                ];
                break;
            default:
                return null;
                break;
        }*/
    }

    /**
     * 编码自定义参数
     */
    public function encodeParams(){
        return base64_encode(json_encode(['uid'=>$this->uid, 'orderNumber'=>$this->orderNumber, 'method'=>$this->method]));
    }
}